package org.dongchao.statistics.exe;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.dongchao.statistics.pojo.RequestResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.common.io.Files;

import lombok.extern.java.Log;

@Component
@Log
public class FileOutPutRequestResultHandler implements RequestResultHandler {

	@Value("${config.startTime}")
	String startTime;

	@Value("${config.endTime}")
	String endTime;

	@Value("${config.out}")
	String out;

	@Override
	public void handler(List<RequestResult> result) {
		Charset chart = Charset.defaultCharset();

		String fileName = out + "/statistics-" + startTime + "-" + endTime + ".txt";
		Path path = Paths.get(fileName);
		log.info("file out save as :" + path.toUri());
		File file = new File(fileName);
		result.forEach(r -> {
			try {
				Files.append(r.outPutLine(), file, chart);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

}
